import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import ProductTypeManagement from '../views/ProductTypeManagement.vue'
import ProductManagement from '../views/ProductManagement.vue'
import DeviceManagement from '../views/DeviceManagement.vue'
import Login from '../views/Login.vue'
import Profile from '../views/Profile.vue'
import LoginRecord from '../views/LoginRecord.vue'
import NotFound from '../views/NotFound.vue'
import NotificationDemo from '../views/NotificationDemo.vue'
import Dashboard from '../views/Dashboard.vue'

// 路由配置
export const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }
  },
  {
    path: '/product-types',
    name: 'ProductTypeManagement',
    component: ProductTypeManagement,
    meta: { requiresAuth: true }
  },
  {
    path: '/products',
    name: 'ProductManagement',
    component: ProductManagement,
    meta: { requiresAuth: true }
  },
  {
    path: '/devices',
    name: 'DeviceManagement',
    component: DeviceManagement,
    meta: { requiresAuth: true }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: Profile,
    meta: { requiresAuth: true }
  },
  {
    path: '/login-records',
    name: 'LoginRecord',
    component: LoginRecord,
    meta: { requiresAuth: true }
  },
  {
    path: '/notification-demo',
    name: 'NotificationDemo',
    component: NotificationDemo,
    meta: { requiresAuth: true }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: { requiresAuth: true }
  },
  // 捕获所有未匹配的路由，显示404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound,
    meta: { requiresAuth: false }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 导航守卫，用于权限控制
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    // 检查用户是否已登录（从localStorage获取）
    const userInfo = localStorage.getItem('userInfo')
    if (userInfo) {
      // 用户已登录，允许访问
      next()
    } else {
      // 用户未登录，重定向到登录页
      next('/login')
    }
  } else {
    // 不需要认证的路由（如登录页），直接允许访问
    next()
  }
})

export default router